// components/FriendPub/index.js
const app = getApp();
const qiniuUploader = require("./../../utils/qiniuUploader");
var api = require('./../../config/api.js');
var util = require('./../../utils/util.js');

// 初始化七牛相关参数
function initQiniu() {
  var options = {
    region: 'SCN', // 华南区
    domain: 'http://pdg4eya6u.bkt.clouddn.com',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    location: null,
    images: [],
    content: '',
    imgid: 0,
    realList: [],
  },
  /**
   * 组件生命周期
   */
  lifetimes:{
    attached(){
      let postdata = wx.getStorageSync('postdata') || null
      if(postdata!=null){
        this.setData(postdata)
      }
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    post(){
      var that = this;
      /**
       * @信息传递到首页
       */
      this.triggerEvent('postlistener',{
        images:this.data.images,
        location:this.data.location,
        content:this.data.content
      })
      
      if (this.data.images.length>0){
        var groupList = [];
        groupList.push({picture_url: this.data.images})

        var postData = {}
        postData.groupList = JSON.stringify(groupList)
        postData.uId = app.globalData.userInfo.uCode
        postData.belongId = 'comment'

        util.myRequest(api.ResetPhotos, postData, function (data) {
          that.addComment(data.data);
        });
      }else{
        that.addComment(0);
      }
      
    },
    addComment: function(pgId){
      var postData = {};
      postData.token = app.globalData.userInfo.token;
      postData.cPid = 0;
      postData.cContent = this.data.content;
      postData.pgId = pgId
      util.myRequest(api.AddComment, postData, function(data){
        wx.navigateBack();
      });
    },
    chooseImage() {
      var that = this
      wx.chooseImage({
        count: 3, //默认9
        sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          initQiniu();

          that.upLoadImage(tempFilePaths, 0, [], function(photoUrlArray) {
            that.setData({images: photoUrlArray})
          });
          }
      });
    },
    // 上传图片
    upLoadImage: function(photos, index, photoUrl, callback) {

      if (photos.length == index) {
        wx.hideLoading();
        callback(photoUrl);
        return;
      }

      var that = this;

      var url = api.QiniuTokenInfo + '/' + app.globalData.userInfo.token;
      util.myRequest(url, false, function(data) {
        //////////////////////////
        var filePath = photos[index];

        setTimeout(function(){
          wx.hideLoading();
          wx.showLoading({
            title: '正在上传' + (index + 1) + '/' + photos.length,
          });
        }, 0);

        // 交给七牛上传
        qiniuUploader.upload(filePath, (res) => {
            wx.hideLoading();
            console.log('upload callback')
            console.log(res)
            // photoUrl.push(res.imageURL);
            photoUrl.push(data.data.url);
            
            that.upLoadImage(photos, index + 1, photoUrl, callback)
            // wx.showToast({
            //   title: '第' + (i + 1) + '张完成上传',
            //   icon: 'loading',
            //   duration: 1000
            // })
          }, (error) => {
            wx.hideLoading();
            console.error('error: ' + JSON.stringify(error));
          }, {
            uptoken: data.data.token,
            key: data.data.name,
            region: 'SCN', // 华南区
          }, // 可以使用上述参数，或者使用 null 作为参数占位符
          (progress) => {
            // console.log('上传进度', progress.progress)
            // console.log('已经上传的数据长度', progress.totalBytesSent)
            // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
          }, cancelTask => that.setData({
            cancelTask
          })
        );
        //////////////////////////
      });
    },
    ViewImage(e) {
      wx.previewImage({
        urls: this.data.images,
        current: e.currentTarget.dataset.url
      });
    },
    
    DelImg(e) {

      this.data.images.splice(e.currentTarget.dataset.index, 1);
      this.setData({
        images: this.data.images
      })
    },
    getInputValue(e) {
      this.setData({
        content: e.detail.value
      })
    },
    saveEditOrNot() {
      wx.navigateBack({
        delta: 1
      })
    },

    chooseLocation() {
      let self = this
      wx.chooseLocation({
        success(res) {
          self.setData({
            location: res.name
          })

        }
      })
    }
  }
})